package task5.file;

import task5.Util;

import java.io.*;
import java.net.Socket;

public class FileClient {

    public static void main(String[] args) {
        OutputStream outputStream = null;
        FileInputStream fileInputStream = null;
        InputStream inputStream = null;
        ByteArrayOutputStream byteArrayOutputStream = null;

        try {
            //创建连接
            Socket socket = new Socket("localhost",9002);
            //获取输出流
            outputStream = socket.getOutputStream();
            //读取文件
            fileInputStream=new FileInputStream(new File("./src/task5/file/picture.jpeg"));

            byte[] buffer =new byte[1024];
            int len;
            while ((len=fileInputStream.read(buffer))!=-1){
                outputStream.write(buffer,0,len);
            }

            //通知服务器 已经传输完毕
            socket.shutdownOutput();

            //文件发送完毕，接收服务端返回消息
            inputStream = socket.getInputStream();
            byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer2 = new byte[1024] ;
            int len2;
            while ((len2=inputStream.read(buffer2))!=-1){
                byteArrayOutputStream.write(buffer2,0,len2);
            }
            System.out.println("客户端：" + byteArrayOutputStream.toString());
        } catch (IOException e) {
            e.printStackTrace();
            // 关闭资源
            Util.close(byteArrayOutputStream,inputStream,fileInputStream,outputStream);
        }
    }
}
